package com.thedazzler.droidicon.factory;

import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Position;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import java.io.InputStream;

public class PixelMapFactory {


    /**
     * 通过资源ID获取位图对象，并指定位图统一颜色, 默认图片大小原图片大小
     * @param context Context
     * @param resId 资源 id
     * @param color icon 颜色
     * @return 指定大小及颜色的位图
     */
    public static PixelMap CreatePixelMap(Context context, int resId, int color){
        return CreatePixelMap(context, resId, color, 0, 0);
    }

    /**
     * 通过图片资源ID获取位图对象，并指定位图中非透明像素点为某统一颜色（ color ）
     * @param context Context
     * @param resId 资源 id
     * @param color icon 颜色
     * @param width icon width
     * @param height icon height
     * @return 指定大小及颜色的位图
     */
    public static PixelMap CreatePixelMap(Context context, int resId, int color, int width, int height){
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource(resId);
            ImageSource imageSource = ImageSource.create(drawableInputStream, null);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            if (width>0&&height>0)decodingOptions.desiredSize = new Size(width, height);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            decodingOptions.editable = true;
            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
            width = width <= 0 || height <= 0 ? pixelMap.getImageInfo().size.width : width;
            height = width <= 0 || height <= 0 ? pixelMap.getImageInfo().size.height : height;
            changeColor(pixelMap, width, height, color);
            return pixelMap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if (drawableInputStream != null){
                    drawableInputStream.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static void changeColor(PixelMap pixelMap, int width, int height, int iconColor){
        Position position = new Position(0, 0);
        for(int row=0; row<height; row++){
            for (int queue=0; queue<width; queue++){
                position.posX = queue;
                position.posY = row;
                if (pixelMap.readPixel(position) != 0){
                    pixelMap.writePixel(position, iconColor);
                }
            }
        }
    }

}